package pers.lls.im.core.common.pool;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.RejectedExecutionException;

/**
 * LinkedTransferQueue 能保证更高性能，相比与LinkedBlockingQueue有明显提升
 * LinkedTransferQueue的缺点是没有队列长度控制，需要在外层协助控制
 *
 * @author lihuan
 * @version V1.0 创建时间：2019/8/02
 * Copyright 2019 by landray & STIC
 */
public class ExecutorQueue extends LinkedTransferQueue<Runnable> {

    StandardThreadExecutor threadPoolExecutor;

    public ExecutorQueue() {
        super();
    }

    public void setStandardThreadExecutor(StandardThreadExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public boolean force(Runnable o) {
        if (threadPoolExecutor.isShutdown()) {
            throw new RejectedExecutionException("Executor not running, can't force a command into the queue");
        }
        return super.offer(o);
    }

    @Override
    public boolean offer(Runnable o) {
        int poolSize = threadPoolExecutor.getPoolSize();
        if (poolSize == threadPoolExecutor.getMaximumPoolSize()) {
            return super.offer(o);
        }
        if (poolSize >= threadPoolExecutor.getSubmittedTasksCount()) {
            return super.offer(o);
        }
        if (poolSize < threadPoolExecutor.getMaximumPoolSize()) {
            return false;
        }
        return super.offer(o);
    }

}
